package com.ruoyi.media.createMp.controller;

import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dtflys.forest.annotation.Get;
import com.dtflys.forest.http.ForestCookie;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.media.createMp.domain.MediaCreateWechatMp;
import com.ruoyi.media.forestApi.WechatMpCreateApi;
import com.ruoyi.media.phoneCache.domain.MediaCreateWechatMpPhone;
import com.ruoyi.media.phoneCache.service.IMediaCreateWechatMpPhoneService;
import com.ruoyi.media.tiktokCover.domain.MediaTiktokCover;
import com.ruoyi.media.tiktokCover.domain.vo.MediaTiktokCoverVo;
import com.ruoyi.media.utils.WxUtils;
import com.ruoyi.media.utils.XStringUtils;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.media.createMp.domain.vo.MediaCreateWechatMpVo;
import com.ruoyi.media.createMp.domain.bo.MediaCreateWechatMpBo;
import com.ruoyi.media.createMp.service.IMediaCreateWechatMpService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 快速创建公众号
 *
 * @author dqw
 * @date 2023-05-04
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/media/createWechatMp")
public class MediaCreateWechatMpController extends BaseController {

    private final IMediaCreateWechatMpService iMediaCreateWechatMpService;
    private final WechatMpCreateApi wechatMpCreateApi;
    private final IMediaCreateWechatMpPhoneService mediaCreateWechatMpPhoneService;

    /**
     * 查询快速创建公众号列表
     */
    @SaCheckPermission("media:createWechatMp:list")
    @GetMapping("/list")
    public TableDataInfo<MediaCreateWechatMpVo> list(MediaCreateWechatMpBo bo, PageQuery pageQuery) {
        return iMediaCreateWechatMpService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出快速创建公众号列表
     */
    @SaCheckPermission("media:createWechatMp:export")
    @Log(title = "快速创建公众号", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(MediaCreateWechatMpBo bo, HttpServletResponse response) {
        List<MediaCreateWechatMpVo> list = iMediaCreateWechatMpService.queryList(bo);
        ExcelUtil.exportExcel(list, "快速创建公众号", MediaCreateWechatMpVo.class, response);
    }

    /**
     * 获取快速创建公众号详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("media:createWechatMp:query")
    @GetMapping("/{id}")
    public R<MediaCreateWechatMpVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iMediaCreateWechatMpService.queryById(id));
    }

    /**
     * 新增快速创建公众号
     */
    @SaCheckPermission("media:createWechatMp:add")
    @Log(title = "快速创建公众号", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody MediaCreateWechatMpBo bo) {
        return toAjax(iMediaCreateWechatMpService.insertByBo(bo));
    }

    /**
     * 创建公众号
     */
    @SaCheckPermission("media:createWechatMp:add")
    @GetMapping("/createMp/{ids}")
    public R<Void> createMp(@NotEmpty(message = "主键不能为空")@PathVariable Long[] ids) {
        return R.ok(iMediaCreateWechatMpService.createAccount(Arrays.asList(ids)));
    }

    /**
     * 修改快速创建公众号
     */
    @SaCheckPermission("media:createWechatMp:edit")
    @Log(title = "快速创建公众号", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody MediaCreateWechatMpBo bo) {
        return toAjax(iMediaCreateWechatMpService.updateByBo(bo));
    }


    /**
     * 删除快速创建公众号
     *
     * @param ids 主键串
     */
    @SaCheckPermission("media:createWechatMp:remove")
    @Log(title = "快速创建公众号", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iMediaCreateWechatMpService.deleteWithValidByIds(Arrays.asList(ids), true));
    }


   /**
     * 根据类型获取二维码
     * @param jsonData 主键
     * @return 二维码图片的byte数组
     */
    @GetMapping("/getQRCodeImage/{jsonData}")
    public R<?> getQRCodeImage(@NotNull(message = "主键不能为空") @PathVariable String jsonData) {
        JSONObject data =   JSONObject.parseObject(jsonData);
        Long id =  data.getLong("id");
        int type =  data.getInteger("type");  //法人二维码 26  管理员二维码 22
        try{
            return R.ok(iMediaCreateWechatMpService.getQRCodeImage(id,type));
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.fail("获取二维码失败！");
    }



    /**
     * 获取二维码结果
     *
     * @param jsonData 主键
     * @return 二维码图片的byte数组
     */
    @GetMapping("/getQRCodeRes/{jsonData}")
    public R<?> getQRCodeRes(@NotNull(message = "参数不能为空") @PathVariable String jsonData) {
        JSONObject data = JSONObject.parseObject(jsonData);
        String id = data.getString("id"); //主键
        String ticket = data.getString("ticket"); //二维码参数
        try{
            MediaCreateWechatMp mediaCreateWechatMp = iMediaCreateWechatMpService.getById(id);
            List<ForestCookie>  forestCookieList =  WxUtils.resetForestCookie(mediaCreateWechatMp.getCookies());
            return R.ok(wechatMpCreateApi.getQRCodeRes(ticket,Math.random(),((forestRequest, forestCookies) -> {
                forestCookies.addAllCookies(forestCookieList);
            })));
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.fail("获取二维码状态错误！");
    }



    /**
     * 获取管理员手机验证码
     * @param id 主键
     * @return
     */
    @GetMapping("/getSystemPhoneCache/{id}")
    public R<?> getSystemPhoneCache(@NotNull(message = "主键不能为空") @PathVariable String id) {
        MediaCreateWechatMp mediaCreateWechatMp = iMediaCreateWechatMpService.getById(id);
        List<ForestCookie> forestCookieList =WxUtils.resetForestCookie(mediaCreateWechatMp.getCookies());
        Map<String,Object> params = new HashMap<>();
        params.put("token",null);
        params.put("lang","zh_CN");
        params.put("f","json");
        params.put("ajax",1);
        params.put("random",Math.random());
        params.put("form","mobile");
        params.put("action","set");
        params.put("mobile","+86" + mediaCreateWechatMp.getSystemPhone());
        params.put("register_method",3);
        String res = wechatMpCreateApi.getSystemPhoneCache(params,((forestRequest, forestCookies) -> {
            forestCookies.addAllCookies(forestCookieList);
        }));
        if(JSONObject.parseObject(res).getJSONObject("base_resp").getInteger("ret") == 0){
            return R.ok("发送成功！");
        }
        return R.fail("发送失败，请重试！");
    }


    /**
     * 根据选中数据一键注册所有公众号
     * @param ids 主键串
     */
    @GetMapping("batchCreateMp/{ids}")
    public R<?> batchCreateMp(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        iMediaCreateWechatMpService.batchCreateMp(Arrays.asList(ids));
        return R.ok("执行成功！");
    }



    /**
     * 根据选中数据一键提交资料
     * @param ids 主键串
     */
    @GetMapping("batchCreateSubmit/{ids}")
    public R<?> batchCreateSubmit(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        iMediaCreateWechatMpService.batchCreateSubmit(Arrays.asList(ids));
        return R.ok("执行成功！");
    }



    /**
     * 获取他信验证码
     * @param ids 主键串
     */
    @GetMapping("getPhoneCacheCode/{ids}")
    public R<?> getPhoneCacheCode(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        List<Long> idsList = Arrays.asList(ids);
        //获取他信登录凭据
        String tokenStr = wechatMpCreateApi.loginTX(); //获取登录凭据
        for(int i = 0 ;i < idsList.size();i++ ){
            //已发送的账号
//            if(RedisUtils.getCacheObject("sendPhone-" + idsList.get(i)) != null){
//                throw new RuntimeException(idsList.get(i) + "发送过于频繁，一分钟之内不可再次发送验证码");
//            }
            String token = tokenStr.split("\\|")[1];
            //获取手机号
            LambdaQueryWrapper<MediaCreateWechatMpPhone> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MediaCreateWechatMpPhone::getIsUse,0);
            List<MediaCreateWechatMpPhone> mediaCreateWechatMpPhones = mediaCreateWechatMpPhoneService.list(queryWrapper);
            if(mediaCreateWechatMpPhones.size() < 1){
                throw new RuntimeException("号码池号码已用完！");
            }
            MediaCreateWechatMpPhone mediaCreateWechatMpPhone = mediaCreateWechatMpPhones.get(0); //获取查询后的第一个手机号
            mediaCreateWechatMpPhone.setIsUse(1);
            mediaCreateWechatMpPhoneService.updateById(mediaCreateWechatMpPhone);
            //获取手机号
            String numberStr = wechatMpCreateApi.getPhoneNumber(token,mediaCreateWechatMpPhone.getPhoneNumber());
            if(numberStr.contains("|")){
                String number = numberStr.split("\\|")[1];
                iMediaCreateWechatMpService.getVerifiableCode(idsList.get(i),token,number);
            }else{
                throw new RuntimeException("获取手机号码失败！");
            }
        }
        return R.ok("执行成功！");
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "公众号模板", MediaCreateWechatMpVo.class, response);
    }

    /**
     * 导入数据
     * @param file          导入文件
     * @param updateSupport 是否更新已存在数据
     */
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        ExcelResult<MediaCreateWechatMpVo> result = ExcelUtil.importExcel(file.getInputStream(), MediaCreateWechatMpVo.class, true);
        List<MediaCreateWechatMpVo> mediaCreateWechatMpVos =  result.getList();
        for(MediaCreateWechatMpVo item : mediaCreateWechatMpVos){
            MediaCreateWechatMp mediaCreateWechatMp = BeanCopyUtils.copy(item, MediaCreateWechatMp.class);
            iMediaCreateWechatMpService.save(mediaCreateWechatMp);
        }
        return R.ok(result.getAnalysis());
    }

}
